package com.sise.bl.controller;

import com.sise.bl.entity.PageBean;
import com.sise.bl.entity.Product;
import com.sise.bl.entity.Type;
import com.sise.bl.service.ProductService;
import com.sise.bl.service.TypeService;
import com.sise.bl.utils.RandomUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "/product")
public class ProductController {
    @Autowired
    @Qualifier("productService")
    private ProductService productService;

    @Autowired
    @Qualifier("typeService")
    private TypeService typeService;

    @RequestMapping(value = "/show")
    public ModelAndView show(@RequestParam("tid") String tid, @RequestParam("currentPage") String currentPage,
                             ModelAndView modelAndView) {
        //1.从前端获取当前页数和也容量
        int pageSize = 6;

        int page = 1;
        if (!currentPage.equals("")) {
            page = Integer.parseInt(currentPage);
        }

        //2.调用业务逻辑得到前端需要展示的PageBean
        PageBean<Product> pageBean = productService.findPage(tid, page, pageSize);

        //3.响应即可
        modelAndView.addObject("pageBean", pageBean);
        modelAndView.setViewName("goodsList");
        return modelAndView;
    }

    @RequestMapping(value = "/detail")
    public ModelAndView detail(@RequestParam("pid") String pid, ModelAndView modelAndView) {
        //调用业务逻辑
        Product product = productService.findProductByPid(pid);
        //响应
        modelAndView.addObject("product", product);
        modelAndView.setViewName("goodsDetail");
        return modelAndView;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("product") Product product,
                             @RequestParam("picture") CommonsMultipartFile upload,
                             HttpServletRequest request, Integer typeid) {


//        //获取图片路径，自建相对路径到服务器
//        //实现文件上传
//        //1.获取上传文件的路径  真实路径
//        String uploadPath = request.getServletContext().getRealPath("/static/image");
//        File file = new File(uploadPath);
//        if (!file.exists()) {
//            file.mkdirs();//新建文件夹
//        }
//        System.out.println(uploadPath);
//        //2.文件上传
//        //生成唯一文件名
//        String oldName = mfile.getOriginalFilename();
//
//        List<String> nameList = new ArrayList<>();
//        nameList.add(".jpg");
//        nameList.add(".png");
//        nameList.add(".jpeg");
//
//        String extName = oldName.substring(oldName.lastIndexOf("."));
//        if (!nameList.contains(extName)) {
//            modelAndView.addObject("msg", oldName + "不符合文件上传的规则！");
//            modelAndView.setViewName("message");
//            return modelAndView;
//        }
//
//        String newName = RandomUtils.newFileName(oldName);
//        //生成二级、三级目录 实现散列存储
//        String newPath = RandomUtils.newFilePath(uploadPath, oldName);
//        System.out.println(newPath);
//        String bimage = newPath + "\\" + newName;
//        mfile.write(bimage);
//        System.out.println(bimage);
//        String newbimage = newPath.substring(newPath.indexOf("\\static")) + "\\" + newName;

//获取文件保存目录
        ServletContext servletContext = request.getSession().getServletContext();
        String path = servletContext.getRealPath("/static/image");
        //获取文件的名称
        String originalFilename = upload.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = System.currentTimeMillis() + ext;

        String savePath = path+"/"+filename;
        try {

            FileUtils.writeByteArrayToFile(new File(savePath), upload.getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置文件的路径
        product.setPimage("static/image/" + filename);

        ModelAndView modelAndView = new ModelAndView();

        Type type = typeService.queryTypeByid(typeid);
        if (type == null) {
            modelAndView.addObject("msg", "添加错误，请选择类别！！！");
            modelAndView.setViewName("message");
            return modelAndView;
        }
        type.getProducts().add(product);
        product.setType(type);
        product.setPtime(new Date());

        int result = productService.saveProduct(product);
        if (result == 0) {
            modelAndView.addObject("msg", "添加错误，请稍后重试！！！");
            modelAndView.setViewName("message");
            return modelAndView;
        }
        modelAndView.setViewName("/admin/addGoods");
        return modelAndView;
    }

}
